#! -*- coding:utf-8 -*-
import fcntl
import logging
from common import orm
from common.black_account.model import WithdrawBlack, WITHDRAW_BLACK_GROUP, WITHDRAW_BLACK_STATUS, WITHDRAW_BLACK_TYPE
from django.core.management.base import BaseCommand
from common.transaction.model import TRANSACTION_TYPE
from common.transaction.db import get_sharding_transaction_table

_SINGLE_READS = 20000
_LOGGER = logging.getLogger('worker')


class Command(BaseCommand):
    def start(self):
        black_lists = WithdrawBlack.query.filter(WithdrawBlack.money > 0,
                                                 WithdrawBlack.type.in_(
                                                     WITHDRAW_BLACK_GROUP['withdraw_black_list'])).all()
        for black_list in black_lists:
            if black_list.type == WITHDRAW_BLACK_TYPE.BLACK_PHONE:
                continue
            transaction_table = get_sharding_transaction_table(int(black_list.type_account))
            amount = orm.session.query(orm.func.sum(transaction_table.price)). \
                filter(transaction_table.user_id == int(black_list.type_account)). \
                filter(transaction_table.type == TRANSACTION_TYPE.BALANCE_BUY).\
                filter(transaction_table.created_at > black_list.created_at).first()[0]
            if amount and int(black_list.money) <= abs(amount):
                black_list.status = WITHDRAW_BLACK_STATUS.INVALID
                black_list.save()

    def handle(self, days_ago=1, **kwargs):
        try:
            f = open('/tmp/flock_disable_withdraw_black', 'w')
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            self.start()
            fcntl.flock(f, fcntl.LOCK_UN)
        except Exception as e:
            print e
            _LOGGER.exception('user award error, %s', e)
